package org.example.service.impl;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.utils.ReflectUtils;

import java.io.Serializable;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


public class CacheServiceImpl<M extends BaseMapper<T>, T> extends ServiceImpl<M, T> {

    public final Map<String, T> CACHE_MAP = new ConcurrentHashMap<>();

    @Override
    public T getById(Serializable id) {
        T value = CACHE_MAP.get(id.toString());
        if (value != null)
            return value;
        T t = super.getById(id);
        if (t != null) {
            if (id != null) {
                CACHE_MAP.put(id.toString(), t);
            }
        }
        return t;
    }

    @Override
    public boolean updateById(T entity) {
        boolean update = super.updateById(entity);

        if (update) {
            //从泛型中拿到tableid
            Object id = ReflectUtils.reflectObjectId(entity);
            if (id != null) {
                CACHE_MAP.remove(id.toString());
            }
        }

        return update;
    }

    public void clearCache() {
    }

}
